package com.crm.service.impl;

import com.crm.domain.dto.BuesinessStaticsQueryDto;
import com.crm.domain.vo.BusinessChangeVO;
import com.crm.mapper.IndexMapper;
import com.crm.service.IndexService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class IndexServiceImpl implements IndexService {
    @Autowired
    private IndexMapper indexMapper;

    /**
     * 商机转换率统计
     * @param buesinessStaticsQueryDto
     * @return
     */
    @Override
    public List<BusinessChangeVO> businessChangeStatistics(BuesinessStaticsQueryDto buesinessStaticsQueryDto) {
    //获取总的商机数量
        int all = indexMapper.getAll(buesinessStaticsQueryDto.getBeginCreateTime(),buesinessStaticsQueryDto.getEndCreateTime());
        System.err.println("商机all:" + all);
        //获取转换商机数据
        List<BusinessChangeVO> volist = indexMapper.getVOlist(buesinessStaticsQueryDto.getBeginCreateTime(),buesinessStaticsQueryDto.getEndCreateTime());
        System.err.println(volist);

        //计算转化百分比
        List<BusinessChangeVO> collect = volist.stream().map(vo -> {
            vo.setRadio(getRadio(all, vo.getNum()));
            return vo;
        }).collect(Collectors.toList());

        return collect;
    }

    /**
     * 计算转化率
     * @param all
     * @param num
     * @return
     */
    private BigDecimal getRadio(Integer all, Long num) {
        if (all.intValue() == 0) {
            return new BigDecimal(0);
        }
        BigDecimal numBigDecimal = new BigDecimal(num);
        BigDecimal allBigDecimal = new BigDecimal(all);
        BigDecimal divide = numBigDecimal.divide(allBigDecimal, 4, BigDecimal.ROUND_HALF_UP);
        return divide.multiply(new BigDecimal(100));
}

    @Override
    public List<BusinessChangeVO> salesStatistic(BuesinessStaticsQueryDto buesinessStaticsQueryDto) {
        //获取总的线索数量
        int all = indexMapper.getCluesNums(buesinessStaticsQueryDto.getBeginCreateTime(),buesinessStaticsQueryDto.getEndCreateTime());
        System.err.println("线索all:" + all);
        //获取转换线索数据
        List<BusinessChangeVO> volist = indexMapper.getClueVOlist(buesinessStaticsQueryDto.getBeginCreateTime(),buesinessStaticsQueryDto.getEndCreateTime());
        System.err.println(volist);

        List<BusinessChangeVO> collect = volist.stream().map(vo -> {
            vo.setRadio(getRadio(all, vo.getNum()));
            return vo;
        }).collect(Collectors.toList());

        return collect;

    }
}
